package com.ccc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccc.dto.Result;
import com.ccc.dto.UserDTO;
import com.ccc.entity.Blog;
import com.ccc.entity.User;
import com.ccc.mapper.BlogMapper;
import com.ccc.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccc.service.IUserService;
import com.ccc.utils.RedisConstants;
import com.ccc.utils.SystemConstants;
import com.ccc.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryHotBog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            setBlogUser(blog);
            blog.setIsLike(getLiked(blog.getId()));
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if(blog == null){
            return Result.fail("笔记不存在!");
        }
        setBlogUser(blog);
        blog.setIsLike(getLiked(id));
        return Result.ok(blog);
    }

    @Override
    public Result likeBlog(Long id) {
        Long userId = UserHolder.getUser().getId();
        //1 判断用户是否点赞了
        if(userId == null){
            return Result.fail("请先登录!");
        }
        //1.1 从redis的set集合(博客id与点赞用户)判断
        Boolean liked = getLiked(id);
        if(BooleanUtil.isFalse(liked)){
            //2 未点赞:更新数据库,点赞数+1,isLike=true,添加set
            Boolean success =  update().setSql("liked = liked + 1").eq("id", id).update();
            if(BooleanUtil.isTrue(success)){
                stringRedisTemplate.opsForZSet()
                        .add(RedisConstants.BLOG_LIKED_KEY + id,
                                userId.toString(),
                                System.currentTimeMillis());
            }
        }
        else {
            //3 已点赞:更新数据库,点赞数-1,islike=false,移除set
            Boolean success =  update().setSql("liked = liked - 1").eq("id", id).update();
            if(BooleanUtil.isTrue(success)){
                stringRedisTemplate.opsForZSet()
                        .remove(RedisConstants.BLOG_LIKED_KEY + id,
                                userId.toString());
            }
        }
            return Result.ok();

    }

    @Override
    public Result queryBlogLikes(Long id) {
        //返回排行榜top5
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(RedisConstants.BLOG_LIKED_KEY + id, 0, 4);
        if(top5 == null){
            return Result.ok();
        }
        List<Long> userIds = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        //使用拼接字符串解决默认排序问题
        String str = StrUtil.join( ",",userIds);
        List<UserDTO> userDTOS = userService
                .query().in("id",userIds).last("ORDER BY FIELD( id,"+str+")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);

    }

    private Boolean getLiked(Long id) {
        Long userId = UserHolder.getUser().getId();
        if(userId == null){
            return false;
        }
        return stringRedisTemplate.opsForZSet()
                .score(RedisConstants.BLOG_LIKED_KEY + id.toString(), userId.toString())
                != null;
    }

    private void setBlogUser(Blog blog) {
        User user = userService.getById(blog.getUserId());
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
